package org.codefinger.dao;

import java.util.Map;

import org.codefinger.dao.impl.DataAccesser;
import org.codefinger.dao.impl.QueryParam;
import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.TableInfo;
import org.codefinger.dao.impl.sql.Where;

public class DeleteWhere implements Deleter {

	private DataAccesser	dataAccesser;

	private TableInfo		tableInfo;

	private Where			where;

	public DeleteWhere(DataAccesser dataAccesser, TableInfo tableInfo, String condition) {
		super();
		this.dataAccesser = dataAccesser;
		this.tableInfo = tableInfo;
		this.where = dataAccesser.createWhere(condition, 0);
	}

	@Override
	public int execute(Object... params) {
		QueryParam queryParam = new QueryParam(params);
		SQLVisitor visitor = new SQLVisitor(queryParam);
		visitor.appendSQL(tableInfo.getDeleteAllSQL());
		where.matchVisit(visitor);
		return dataAccesser.executeUpdate(visitor.getSQL(), visitor.getParams());
	}
	
	@Override
	public int execute(Map<String, Object> params) {
		QueryParam queryParam = new QueryParam(params);
		SQLVisitor visitor = new SQLVisitor(queryParam);
		visitor.appendSQL(tableInfo.getDeleteAllSQL());
		where.matchVisit(visitor);
		return dataAccesser.executeUpdate(visitor.getSQL(), visitor.getParams());
	}

	@Override
	public DeleterChain putParam(String name, Object value) {
		final QueryParam queryParam = new QueryParam();
		queryParam.setNamedParam(name, value);
		return new DeleterChain() {

			@Override
			public DeleterChain putParam(String name, Object value) {
				queryParam.setNamedParam(name, value);
				return this;
			}

			@Override
			public int execute() {
				SQLVisitor visitor = new SQLVisitor(queryParam);
				visitor.appendSQL(tableInfo.getDeleteAllSQL());
				where.matchVisit(visitor);
				return dataAccesser.executeUpdate(visitor.getSQL(), visitor.getParams());
			}

		};
	}

}
